<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="elements"
        noimmediate
        @submit="handleSearch"
        @reset="handleReset"
      >
        <Button v-if="!imageShow" type="plain" @click="handleEdit"
          >绩效申述</Button
        >
        <Button
          icon="icon-daochu"
          :btn-loading="dcLoading"
          @click="handleDealExcel"
          >导出</Button
        >
      </FilterForm>
    </Container>
    <Container height="fill">
      <div class="wraper">
        <div v-if="imageShow" class="image-srcc">
          <img src="../../../assets/image/archived.png" alt="" />
        </div>
        <Table
          :columns="tableColumns"
          :loading="tableLoading"
          :data="tableData"
          :hide-pagination="true"
          :show-summary="true"
          :summary-method="getSummaries"
        >
          <template #initialScore="{row}">
            <div class="row-hearf" @click="handleClick(101,row)">{{ row.initialScore }}</div>
          </template>
          <template #ductScore="{row}">
            <div class="row-hearf" @click="handleClick(102,row)">{{ row.ductScore }}</div>
          </template>
          <template #supervisionScore="{row}">
            <div class="row-hearf" @click="handleClick(103,row)">{{ row.supervisionScore }}</div>
          </template>
          <template #opScore="{row}">
            <div class="row-hearf" @click="handleClick(104,row)">{{ row.opScore }}</div>
          </template>
          <template #manualScore="{row}">
            <div class="row-hearf" @click="handleClick(105,row)">{{ row.manualScore }}</div>
          </template>
          <template #scale="{row}">
            {{ (row.scale * 100).toFixed(2) }}%
          </template>
        </Table>
      </div>
      <!-- 新增、编辑 -->
      <Drawer
        ref="drawerRef"
        :title="title"
        :visible.sync="showDrawer"
        width="420px"
        :footer-btns="[
          {
            text: '确认',
            type: 'primary',
            loading: qrLoading,
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @submit="handleSubmit"
        @cancel="showDrawer = false"
      >
        <el-form
          v-if="showDrawer"
          ref="drawerForm"
          :model="drawerForm"
          :rules="drawerRules"
          label-width="120px"
          size="mini"
          class="demo-drawerForm"
        >
          <el-form-item label="申诉周期：" prop="appealCycle">
            <el-select v-model="drawerForm.appealCycle" clearable placeholder="请选择申诉周期">
              <el-option
                v-for="item in this.elements[0].options"
                :key="item.periodSuffix"
                :label="item.periodPull"
                :value="item.periodSuffix">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注：" prop="remark">
            <el-input
              v-model.trim="drawerForm.remark"
              type="textarea"
              placeholder="请输入"
              rows="5"
              maxlength="100"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-form>
      </Drawer>
      <!-- 明细 -->
      <el-dialog
        title="明细"
        :visible.sync="centerDialogVisible"
        top="20vh"
        width="60%"
      >
        <div class="wraper">
          <Table
            :columns="tableColumnsDetail"
            :loading="tableLoadingDetail"
            :data="tableDataDetail"
            :pagination="{
              total: total,
              current: currentPage,
              pageSize: pageSize,
            }"
            @paginationChange="pageChange"
          />
        </div>
        <!-- <div class="dialog-but">
          <el-button @click="handleClaer">取消</el-button>
        </div> -->
      </el-dialog>
    </Container>
  </ContainerGroup>
</template>
<script>
import {
  getAssessmentCyclePull,
  saveOrUpdate
  // getExport
} from '@/api/weight'
import {
  getListByPeriod,
  exportData,
  listByPeriod
} from '@/api/dataCleaning'
import {
  getAssessmentCycleById
} from '@/api/targetManagement'
export default {
  data() {
    return {
      centerDialogVisible: false,
      dcLoading: false,
      qrLoading: false,
      drawerForm: {
        appealCycle: "",
        remark: ""
      },
      drawerRules: {
        appealCycle: [
          { required: true, message: "请选择申诉周期", trigger: "change" },
        ]
      },
      showDrawer: false,
      title: "",
      tableColumns: [
        {
          title: '核算单元名称',
          dataIndex: 'accountingName'
        },
        {
          title: '核算单元编码',
          dataIndex: 'accountingCode'
        },
        {
          title: '核算单元权重',
          dataIndex: 'workloadWeight'
        },
        {
          title: '初始分值',
          dataIndex: 'initialScore',
          type: 'otherTag'
        },
        {
          title: '导管工作量',
          dataIndex: 'ductScore',
          type: 'otherTag'
        },
        {
          title: '督查扣分',
          dataIndex: 'supervisionScore',
          type: 'otherTag'
        },
        {
          title: '内镜手术',
          dataIndex: 'opScore',
          type: 'otherTag'
        },
        {
          title: '人工统计',
          dataIndex: 'manualScore',
          type: 'otherTag'
        },
        // {
        //   title: '工作量权重',
        //   dataIndex: ''
        // },
        {
          title: '季度合计',
          dataIndex: 'totalScore'
        },
        {
          title: '人员编制',
          dataIndex: 'staffCount'
        },
        {
          title: '编制均分',
          dataIndex: 'avgSorce'
        },
        {
          title: '上个周期',
          dataIndex: 'lastCount'
        },
        {
          title: '上升比',
          dataIndex: 'scale',
          type: 'otherTag'
        }
      ],
      tableLoading: false,
      tableData: [],
      newCondition: {},
      elements: [
        {
          key: "cycle",
          label: "周期",
          type: "select",
          itemLabel: "periodPull",
          itemValue: "periodSuffix",
          hideSelectAll: true,
          options: [],
          value: "",
        }
      ],
      imageShow: false,
      btnLoading: false,
      // 明细
      tableColumnsDetail: [
        {
          title: '核算单元',
          dataIndex: 'deptName'
        },
        {
          title: '工作量指标编码',
          dataIndex: 'workloadCode'
        },
        {
          title: '工作量指标名称',
          dataIndex: 'workloadName'
        },
        // {
        //   title: "科室编码",
        //   dataIndex: "deptCodeInfo",
        // },
        // {
        //   title: '开单科室',
        //   dataIndex: 'billDeptNameInfo'
        // },
        // {
        //   title: '执行科室',
        //   dataIndex: 'exeDeptNameInfo'
        // },
        {
          title: '统计项目编码',
          dataIndex: 'projectCode'
        },
        {
          title: '统计项目名称',
          dataIndex: 'projectName'
        },
        {
          title: '点数',
          dataIndex: 'pionts'
        },
        {
          title: '汇总值',
          dataIndex: 'counts'
        },
        {
          title: '分值',
          dataIndex: 'amount'
        }
      ],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableLoadingDetail: false,
      tableDataDetail: [],
      workloadTypeCode: '',
      accountingCode: ''
    };
  },
  // watch: {
  //   imageShow: {
  //     handler(val) {
  //       if (val === true) {
  //         this.tableColumns = [
  //           {
  //             title: "核算单元名称",
  //             dataIndex: "accountingName",
  //           },
  //           {
  //             title: "核算单元编码",
  //             dataIndex: "accountingCode",
  //           },
  //           {
  //             title: "工作量权重",
  //             dataIndex: "workloadWeight",
  //           },
  //           {
  //             title: "考核周期",
  //             dataIndex: "assessmentCycle",
  //           },
  //         ];
  //       } else {
  //         this.tableColumns = [
  //           {
  //             title: "核算单元名称",
  //             dataIndex: "accountingName",
  //           },
  //           {
  //             title: "核算单元编码",
  //             dataIndex: "accountingCode",
  //           },
  //           {
  //             title: "工作量权重",
  //             dataIndex: "workloadWeight",
  //           },
  //           {
  //             title: "考核周期",
  //             dataIndex: "assessmentCycle",
  //           },
  //           {
  //             title: "操作",
  //             dataIndex: "caozuo",
  //             type: "otherTag",
  //             width: 160,
  //           },
  //         ];
  //       }
  //     },
  //   },
  // },
  created() {
    this.getSelect();
  },
  methods: {
    // 是否归档
    getFileInfo() {
      const id = this.elements[0].options.find(item => item.periodSuffix === this.newCondition?.cycle)?.id
      getAssessmentCycleById({
        id: id
      }).then((res) => {
        if (res.code === 200) {
          const { isFile } = res.data
          if (isFile === 1) {
            this.imageShow = true
          } else {
            this.imageShow = false
          }
        }
      })
    },
    getSelect() {
      // 周期
      getAssessmentCyclePull().then((res) => {
        if (res.code === 200) {
          this.elements[0].options = res.data
          const { periodSuffix } = res.data[0]
          this.elements[0].value = periodSuffix
          localStorage.setItem(
            'cycle',
            JSON.stringify(this.elements[0].options)
          )
          this.handleSearch(this.$refs.filterForm.getParms())
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleDealExcel() {
      // 导出字典
      const params = {
        period: this.newCondition?.cycle,
        deptCode: JSON.parse(localStorage.userInfo).accountingCode
        // ids: this.selections.map((item) => item.id)
      }
      this.dcLoading = true
      exportData(params).then((res) => {
        this.dcLoading = false
        this.$utils.downloadFileFun(res, '护理工作量查询.xls')
      })
    },
    // 绩效申诉--保存
    handleSubmit() {
      this.$refs["drawerForm"].validate((valid) => {
        if (valid) {
          const param = {
            assessmentCycleId: this.drawerForm.appealCycle,
            appealContent: this.drawerForm.remark,
            appealCode: JSON.parse(localStorage.userInfo).userCode,
            appealName: JSON.parse(localStorage.userInfo).userName
          };
          // param.id = this.currentRow?.id;
          this.qrLoading = true;
          saveOrUpdate(param).then((res) => {
            this.qrLoading = false;
            if (res.code === 200) {
              this.getData();
              this.showDrawer = false
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 查询
    handleSearch(value) {
      this.newCondition = value;
      this.getFileInfo()
      this.getData();
    },
    // 重置
    handleReset(val) {
      this.handleSearch(val);
    },
    handleEdit() {
      // 绩效申诉
      this.title = "绩效申诉";
      this.$handleSetForm(this.drawerForm, 0);
      this.showDrawer = true;
    },
    // 数据
    getData() {
      const params = {
        period: this.newCondition?.cycle,
        deptCode: JSON.parse(localStorage.userInfo).accountingCode
      }
      this.tableLoading = true
      getListByPeriod(params)
        .then((res) => {
          this.tableLoading = false
          if (res.code === 200) {
            this.tableData = res.data
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {
          this.tableLoading = false
        })
    },
    // 总计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (column.property === 'initialScore') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(4)
          } else {
            sums[index] = 'N/A'
          }
        }
        if (column.property === 'ductScore') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(4)
          } else {
            sums[index] = 'N/A'
          }
        }
        if (column.property === 'supervisionScore') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(4)
          } else {
            sums[index] = 'N/A'
          }
        }
        if (column.property === 'opScore') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(4)
          } else {
            sums[index] = 'N/A'
          }
        }
        if (column.property === 'manualScore') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(4)
          } else {
            sums[index] = 'N/A'
          }
        }
        if (column.property === 'totalScore') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(4)
          } else {
            sums[index] = 'N/A'
          }
        }
        if (column.property === 'staffCount') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(4)
          } else {
            sums[index] = 'N/A'
          }
        }
      })

      return sums
    },
    // 明细
    handleClick(val, row) {
      this.workloadTypeCode = val
      this.accountingCode = row.accountingCode
      this.centerDialogVisible = true
      this.getDataDetail()
    },
    // handleClaer() {
    //   this.centerDialogVisible = false;
    // },
    // 明细分页
    pageChange(payload) {
      this.currentPage = payload.current
      this.pageSize = payload.pageSize
      this.getDataDetail()
    },
    // 明细数据
    getDataDetail() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        period: this.newCondition?.cycle,
        deptCode: this.accountingCode,
        workloadTypeCode: this.workloadTypeCode
      }
      this.tableLoadingDetail = true
      listByPeriod(params)
        .then((res) => {
          this.tableLoadingDetail = false
          if (res.code === 200) {
            this.tableDataDetail = res.data.records
            this.total = res.data.total
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {
          this.tableLoadingDetail = false
        })
    },
  },
};
</script>
<style lang="less" scoped>
.wraper {
  display: flex;
  height: calc(100% - 10px);
  overflow: hidden;
  position: relative;
  .upload-demo {
    .buttons {
      margin: 0px 5px;
      height: 27px;
      margin-top: -1px;
    }
  }
}
/deep/.el-dialog__header {
  padding: 10px 10px 0px 10px;
  padding-bottom: 0px;
}
/deep/.el-dialog__title {
  font-size: 15px;
}
/deep/.el-dialog__headerbtn {
  top: 10px;
}
/deep/.el-dialog__body {
  padding: 10px;
}
.dialog-inherit {
  display: flex;
  flex-direction: row;
  margin: 10px;
  justify-content: center;
  span {
    margin-top: 5px;
  }
}
.dialog-but {
  margin: 10px;
  display: flex;
  flex-direction: row;
  justify-content: right;
}
// /deep/.el-table {
//   position: relative;
// }
.image-srcc {
  width: 60px;
  height: 60px;
  // border: 1px solid red;
  position: absolute;
  top: 5px;
  left: 190px;
  z-index: 2;
  img {
    width: 100%;
    height: 100%;
  }
}
.row-hearf {
  color: #3D92FF;
  cursor: pointer;
}
::v-deep .el-dialog__body {
  height: 500px;
}
</style>
